<template>
  <div class="page-main">
    <query-page
      ref="queryPageRef"
      v-model:selectedKeys="selectedKeys"
      title="询价单确认"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="baseRenderKeys.tableconfigurationitem.formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="
        baseRenderKeys.tableconfigurationitem.newTableRenderKeys
      "
      :loading="isLoading"
      :data="renderData"
      :total="total"
      row-selection-type="checkbox"
      @query-data="getData"
    >
      <template #container-side>
        <a-button
          v-permission="['procurement:inquiry:confiremInquiry']"
          type="primary"
          :disabled="btnDisable"
          @click="confirmOK('batch')"
          >确认</a-button
        >
        <a-button
          v-permission="['procurement:inquiry:batchUpdate']"
          type="text"
          :disabled="btnDisable"
          @click="batchEditFrom"
          >批量修改</a-button
        >
        <a-button
          v-permission="['procurement:inquiry-item:export']"
          type="text"
          @click="exportData"
          >Excel导出</a-button
        >
      </template>
      <template #operate="{ record }">
        <span
          v-permission="['procurement:inquiry:batchUpdate']"
          class="row-btn"
          @click="handelEdit(record)"
          >编辑</span
        >
        <span
          v-permission="['procurement:inquiry:confiremInquiry']"
          class="row-btn"
          @click="confirmOK('row', record)"
          >确认</span
        >
        <span
          v-permission="['procurement:quote-item:selectQuoteItemByPage']"
          class="row-btn"
          @click="detail(record)"
          >详情</span
        >
      </template>
    </query-page>
    <!-- 弹窗 -->
    <popUp
      v-if="popVisible"
      :title-text="popUpTitle"
      @handle-ok="handleOk"
      @handle-cancel="handleCancel"
    >
      <template #content>
        <a-form ref="formRef" :model="form" :rules="formRules">
          <a-row v-if="batchmodifyingflag" :gutter="16">
            <a-col :span="9">
              <a-form-item
                field="linkTel"
                label="计划员电话："
                label-col-flex="120px"
              >
                <a-input v-model="form.linkTel" placeholder="请输入手机号" />
              </a-form-item>
            </a-col>
            <a-col :span="15">
              <a-form-item
                field="quoteDeadlineDate"
                label="报价截止日期："
                label-col-flex="120px"
              >
                <a-date-picker
                  v-model="form.quoteDeadlineDate"
                  :allow-clear="true"
                  value-format="YYYY-MM-DD"
                  style="width: 254px; margin-bottom: 20px"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-if="compileflag" :gutter="16">
            <a-col :span="13">
              <a-form-item
                field="quoteDeadlineDate"
                label="报价截止日期："
                label-col-flex="150px"
              >
                <a-date-picker
                  v-model="form.quoteDeadlineDate"
                  :allow-clear="true"
                  value-format="YYYY-MM-DD"
                  style="width: 254px; margin-bottom: 20px"
                />
              </a-form-item>
            </a-col>
            <a-col :span="10">
              <a-form-item
                field="supplierLinkmanName"
                label="供应商联系人："
                label-col-flex="120px"
              >
                <user
                  v-model="form.supplierLinkmanName"
                  :title="'供应商联系人'"
                  @handle-ok="useChange"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-if="compileflag" :gutter="16">
            <a-col :span="13">
              <a-form-item
                field="supplierLinkmanTel"
                label="供应商联系电话："
                label-col-flex="150px"
              >
                <a-input
                  v-model="form.supplierLinkmanTel"
                  placeholder="请输入供应商联系电话"
                  style="width: 254px"
                />
              </a-form-item>
            </a-col>
            <a-col :span="10">
              <a-form-item
                field="linkTel"
                label="联系电话："
                label-col-flex="120px"
              >
                <a-input v-model="form.linkTel" placeholder="请输入联系电话" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </popUp>
    <!-- 子表单 -->
    <compflagbox
      v-if="inseflag"
      ref="compflagboxRef"
      :conte="listscontext"
      :listtab="liststab"
      @get-datas="handelPlanListNo"
      @close-drawer="closeDrawer"
    >
    </compflagbox>
  </div>
</template>

<!-- inquiry-confirmation -->
<script lang="ts" setup>
  import { ref, onMounted, watch } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { hasDataAndBack } from '@/common/utils/index';
  import queryPage from '@/common/components/query-page/index.vue';
  import {
    selectNormalInquiryPage,
    confirem,
    batchUpdate,
    exportFile,
    // edit,
    pageByInquiryNo,
  } from '@/api/supplier/inquiry-confirmation';
  import user from '@/common/components/search-modal/user.vue';
  import { downFileToExcel } from '@/common/utils/downFile';
  import {
    formRenderConfig,
    formComponentConfig,
  } from './components/formComp/baseFormConfig';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from './components/tableComp/baseTableConfig';
  import { baseRenderKeys } from './components/baseDatainquiry-confirmation';
  import popUp from './components/pop-up.vue';
  import compflagbox from './components/compflag.vue';

  const formRef = ref();
  const selectedKeys = ref([]);
  const isLoading = ref(true);
  const popVisible = ref(false);
  const btnDisable = ref(true);
  const batchmodifyingflag = ref(false);
  const compileflag = ref(false);
  const inseflag = ref(false);
  const total = ref(0);
  const queryPageRef = ref();
  const inquiryNo = ref();
  const compflagboxRef = ref();
  const renderData = ref<any[]>([]);
  interface Rorm {
    quoteDeadlineDate?: string;
    linkTel?: string;
    inquiryNo?: string;
    supplierLinkmanName?: string;
    supplierLinkmanTel?: string;
  }
  const form = ref<Rorm>({
    quoteDeadlineDate: '', // 批量报价截止日期
    linkTel: '', // 计划员电话
    inquiryNo: '',
    supplierLinkmanName: '', // 供应商联系人
    supplierLinkmanTel: '', // 供应商联系电话
  });
  watch(
    selectedKeys,
    (n) => {
      if (n?.length > 0) {
        btnDisable.value = false;
        getInquiryNo(n);
      } else {
        btnDisable.value = true;
      }
    },
    {
      deep: true,
    }
  );
  const formRules = ref({
    linkTel: [
      { required: true, message: '请填写联系电话', trigger: 'blur' },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入有效的手机号',
        trigger: 'blur',
      },
    ],
    quoteDeadlineDate: [
      {
        required: true,
        message: '请选择报价截止日期',
        trigger: 'change',
      },
    ],
    supplierLinkmanName: [
      { required: true, message: '请选择', trigger: 'change' },
    ],
    supplierLinkmanTel: [
      { required: true, message: '请填写', trigger: 'blur' },
    ],
  });
  const btnType = ref('');
  const popUpTitle = ref('');
  const listscontext: any = ref({});
  const liststab = ref({});
  const inquiryNos: any = ref([]);
  const getInquiryNo = (n: any) => {
    inquiryNos.value.length = 0;
    n?.forEach((e: any) => {
      renderData.value?.forEach((item: any) => {
        if (e === item.id) {
          inquiryNos.value.push(item.inquiryNo);
        }
      });
    });
  };
  onMounted(() => {
    getData({});
  });
  const getData = async (queryInfo: object) => {
    renderData.value = [];
    const { data } = await selectNormalInquiryPage(queryInfo);
    renderData.value = data.list;
    total.value = data.total;
    if (
      hasDataAndBack(
        renderData.value,
        total.value,
        queryPageRef.value?.getStatus().pageNo
      )
    ) {
      queryPageRef.value?.setCurrent(queryPageRef.value.getStatus().pageNo - 1);
      getData(queryPageRef.value?.getStatus());
    }
    isLoading.value = false;
  };
  const handelEdit = async (record: any) => {
    popUpTitle.value = '修改';
    batchmodifyingflag.value = false;
    form.value = { ...record };
    btnType.value = '1';
    popVisible.value = true;
    compileflag.value = true;
  };
  const handelPlanListNo = async () => {
    const res = (await pageByInquiryNo({ inquiryNo: inquiryNo.value })) as any;
    if (res.code === 200) {
      listscontext.value = res.data?.list;
    }
    inseflag.value = true;
    compflagboxRef.value.getData();
  };
  const detail = async (record: any) => {
    inquiryNo.value = record.inquiryNo;
    handelPlanListNo();
  };
  const initData = () => {
    liststab.value = baseRenderKeys.tableconfigurationitem.cmTableRenderKeys;
  };
  const useChange = () => {
    formRef.value.validateField(['supplierLinkmanName']);
  };
  // 导出数据
  const exportData = async () => {
    try {
      const { data, fileName }: any = await exportFile(
        queryPageRef.value.getStatus()
      );
      downFileToExcel(fileName, data);
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Message.error(`出现异常！${error}`);
    } finally {
      isLoading.value = false;
    }
  };
  // 批量修改
  const batchEditFrom = () => {
    btnType.value = '2';
    popUpTitle.value = '批量修改';
    popVisible.value = true;
    batchmodifyingflag.value = true;
    form.value = {
      linkTel: '',
      quoteDeadlineDate: '',
    };
    compileflag.value = false;
  };
  // 弹窗确认
  const handleOk = async (flag: boolean, done: any) => {
    const val = await formRef.value.validate();
    if (!val) {
      const params = {
        linkTel: form.value.linkTel,
        quoteDeadlineDate: form.value.quoteDeadlineDate,
      };
      const items = {
        inquiryVO: btnType.value === '2' ? { ...params } : { ...form.value },
        inquiryNos:
          btnType.value === '2' ? inquiryNos.value : [form.value.inquiryNo],
      };
      batchEdit(items);
      popVisible.value = flag;
    } else {
      done(false);
    }
  };
  const confirmOK = async (type: string, row?: any) => {
    const codes: any = type === 'row' ? [row?.inquiryNo] : inquiryNos.value;
    const res = (await confirem(codes)) as any;
    if (res.code === 200 && res.data) {
      Message.success('操作成功');
      getData(queryPageRef.value.getStatus());
      selectedKeys.value.length = 0;
    } else if (!res.data) {
      Message.warning(res.message);
    }
  };
  const batchEdit = async (items: any) => {
    const res = (await batchUpdate(items)) as any;
    if (res.code === 200) {
      Message.success('操作成功');
      getData(queryPageRef.value.getStatus());
      formRef.value.resetFields();
      selectedKeys.value.length = 0;
    }
  };
  // 弹窗取消
  const handleCancel = (flag: boolean) => {
    formRef.value.resetFields();
    popVisible.value = flag;
  };

  // 子表单取消
  const closeDrawer = () => {
    inseflag.value = false;
  };

  onMounted(() => {
    initData();
  });
</script>

<style lang="less" scoped>
  .radio-ara {
    display: flex;
    justify-content: space-between;
    width: 17.5%;
  }

  :deep(.arco-picker) {
    margin-bottom: 0 !important;
  }

  .row-btn {
    color: #1e89ff;
    cursor: pointer;
  }

  .disclum {
    display: flex;
    flex-direction: column;
  }

  .disflex {
    display: flex;
    align-items: center;
    justify-content: space-between;
    text-align: center;
  }

  :deep(.arco-btn-text.arco-btn-disabled) {
    color: var(--color-text-4) !important;
    background-color: var(--color-secondary-disabled) !important;
    border: 1px solid transparent !important;
    cursor: not-allowed !important;
  }

  :deep(.arco-btn-text) {
    margin-right: 8px;
    color: var(--color-text-2) !important;
    background-color: var(--color-secondary) !important;
    border: 1px solid transparent !important;
  }
</style>
